package com.boot.web.exception.handler;

import com.boot.web.exception.GlobalException;
import com.boot.web.exception.ModuleExceptionHandler;
import com.boot.web.http.HttpModel;
import lombok.EqualsAndHashCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 为 {@link GlobalException} 提供错误处理
 * @date 2020/2/16 20:16
 **/
@Component
@EqualsAndHashCode
public class GlobalExceptionHandler implements ModuleExceptionHandler {

    @Override
    public boolean support(Exception e) {
        return e instanceof GlobalException;
    }

    @Override
    public int order() {
        return 98;
    }

    @Override
    public ResponseEntity<HttpModel<Object>> handle(Exception e) {
        GlobalException exception = (GlobalException) e;
        Throwable rootCause = exception.getRootCause();
        if (rootCause == null && exception.getRawMessage() == null) {
            return new ResponseEntity<>(HttpModel.<Object>builder().code(exception.getStatus().getStatus()).msg(exception.getStatus().getDescription()).build(),
                    exception.getHttpStatus());
        } else if (rootCause == null) {
            return new ResponseEntity<>(
                    HttpModel.<Object>builder().code(exception.getStatus().getStatus()).msg(exception.getStatus().getDescription()
                            + ',' + exception.getRawMessage()).build(),
                    exception.getHttpStatus());
        } else {
            return new ResponseEntity<>(
                    HttpModel.<Object>builder().code(exception.getStatus().getStatus()).msg(exception.getStatus().getDescription()
                            + ',' + rootCause.getMessage()).build(),
                    exception.getHttpStatus());
        }
    }
}
